package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.tangyh.basic.utils.DateUtils;
import top.tangyh.lamp.care.entity.BObsvRecord;
import top.tangyh.lamp.care.entity.BPatEvent;
import top.tangyh.lamp.care.service.*;
import top.tangyh.lamp.care.vo.result.TemperateIODataVO;
import top.tangyh.lamp.care.vo.result.TepPipeUseRecordVO;
import top.tangyh.lamp.common.constant.ModelItemConstant;
import top.tangyh.lamp.common.utils.PDateUtils;
import top.tangyh.lamp.common.utils.YDateUtils;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author: zqb
 * @date: 2024/7/25 08:53
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TemperatureDetailServiceImpl implements TemperatureDetailService {

    private final BObsvRecordService bObsvRecordService;

    private final BPatEventService bPatEventService;

    private final BIoRecordService bIoRecordService;


    private  final BPipeUseRecordService bPipeUseRecordService;

    @Override
    public Map<String, List<BObsvRecord>> getDevTwdObsvRecord(String patientIdent, String hospitalNumber, String rkTimeStr, String cYTimeStr) {
        Date startTime = YDateUtils.strToDate(rkTimeStr, YDateUtils.DATE_TIME_PATTERN);
        Date endTime = YDateUtils.strToDate(cYTimeStr, YDateUtils.DATE_TIME_PATTERN);
        return bObsvRecordService.getDevTwdObsvRecord(patientIdent, hospitalNumber, startTime, endTime);
    }

    @Override
    public Map<String, List<BObsvRecord>> getCollectsTw(String hospitalNumber, Long rkTimeLong, Long cYTimeLong) {
        List<BObsvRecord> listTempera = bObsvRecordService.getTemperaListData(hospitalNumber, rkTimeLong, cYTimeLong);


        Map<String, List<BObsvRecord>> collectsTempera = listTempera.stream().collect(Collectors.groupingBy(BObsvRecord::getDiffHour));

        Map<String, List<BObsvRecord>> collectsTemperaResult = new ConcurrentHashMap<>();
        BigDecimal tw = BigDecimal.valueOf(37.4);

        BigDecimal tw1 = BigDecimal.valueOf(35);
        BigDecimal tw2 = BigDecimal.valueOf(38.4);

        for (Map.Entry<String, List<BObsvRecord>> entry : collectsTempera.entrySet()) {
            //取集合中某个属性最大的那条记录 体温值
            Optional<BObsvRecord> optional = entry.getValue().stream().filter(code -> !code.getObsvCode().equals(ModelItemConstant.GCX_WLJWJW) && !code.getObsvCode().equals(ModelItemConstant.GCX_CLGJ) && StringUtil.isNotEmpty(code.getPropValue())).max(Comparator.comparing(BObsvRecord::getPropValue));
            BObsvRecord maxRecord;
            if (optional.isPresent()) {
                maxRecord = optional.get();

                BigDecimal propvalue = new BigDecimal(maxRecord.getPropValue());

                Integer compareV = propvalue.compareTo(tw);
                Integer compareV2 = propvalue.compareTo(tw1);
                Integer compareV3 = propvalue.compareTo(tw2);

                List<BObsvRecord> twoList = new LinkedList<>();
                List<BObsvRecord> listAllItemData = entry.getValue();

                //当体温大于等于38.4摄氏度 优先级1  ------------
//                当体温大于等于38.4，
//                如果没有配物理降温，就取温度最高的
//                        如果有温度配了物理降温
//                1，配了一个物理降温 就取配置物理降温的那个体温，且体温大于等于38.4
//                2，配了多个物理降温，就取物理降温最高的那个体温，且体温也是大于等于38.4
                //大于等于38.4
                if (compareV3 == 1 || compareV3 == 0) {
                    List<BObsvRecord> list_384 = entry.getValue();

                    List<BObsvRecord> listWljwRecords = list_384.stream()
                            .filter(x -> x.getObsvCode().equals(ModelItemConstant.GCX_WLJWJW) && StringUtil.isNotEmpty(x.getPropValue())).collect(Collectors.toList());

                    //说明有体温 有物理降温的值
                    if (listWljwRecords.size() > 0) {
                        BigDecimal max = new BigDecimal(listWljwRecords.stream().map(BObsvRecord::getPropValue).max((x1, x2) -> x1.compareTo(x2)).get());
                        BObsvRecord maxRecordOne = new BObsvRecord();
                        for (int i = 0; i < listWljwRecords.size(); i++) {
                            BObsvRecord record = listWljwRecords.get(i);
                            if (record.getPropValue().equals(max.toString())) {
                                maxRecordOne = record;
                            }
                        }
                        String recTimeStr = maxRecordOne.getRecTimeStr();

                        List<BObsvRecord> recordWdCode = listAllItemData.stream()
                                .filter(x -> recTimeStr.equals(x.getRecTimeStr()) && !x.getObsvCode().equals(ModelItemConstant.GCX_WLJWJW)).collect(Collectors.toList());
                        twoList.add(maxRecordOne);
                        twoList.addAll(recordWdCode);
                        collectsTemperaResult.put(entry.getKey(), twoList);
                        continue;
                    } else {
                        List<BObsvRecord> recordWdCode = listAllItemData.stream()
                                .filter(x -> maxRecord.getRecTimeStr().equals(x.getRecTimeStr()) && !x.getObsvCode().equals(ModelItemConstant.GCX_T) && !x.getObsvCode().equals(ModelItemConstant.GCX_WLJWJW)).collect(Collectors.toList());
                        twoList.addAll(recordWdCode);

                        // 当体温大于等于37.4° 当体温>37.4℃，且时间段内有一次或多次测温，则取最高体温值
                        twoList.add(maxRecord);
                        collectsTemperaResult.put(entry.getKey(), twoList);
                        continue;
                    }


                }

                //当体温小于35摄氏度 显示不升  优先级2
                boolean is_low_35 = false;
                List<BObsvRecord> list_35 = entry.getValue();
                for (int i = 0; i < list_35.size(); i++) {
                    BObsvRecord record = list_35.get(i);
                    if (record.getObsvCode().equals(ModelItemConstant.GCX_T)) {
                        if (StringUtil.isNotEmpty(record.getPropValue())) {
                            BigDecimal propvalue_35 = new BigDecimal(record.getPropValue());
                            Integer compare_35 = propvalue_35.compareTo(tw1);
                            if (compare_35 == -1) {
                                is_low_35 = true;
                                break;
                            }
                        }
                    }
                }
                if (is_low_35) {
                    BObsvRecord record_bs = new BObsvRecord();
                    record_bs.setIsNotRiseStr("不升");
                    twoList.add(record_bs);
                    collectsTemperaResult.put(entry.getKey(), twoList);
                    continue;
                }


                //当体温大于等于37.4° (如果四个体温值最大值的记录大于 37.4°) 优先级3
                if (compareV == 1) {

                    //取体温对应的code
                    List<BObsvRecord> recordWdCode = listAllItemData.stream()
                            .filter(x -> maxRecord.getRecTimeStr().equals(x.getRecTimeStr()) && !x.getObsvCode().equals(ModelItemConstant.GCX_T) && !x.getObsvCode().equals(ModelItemConstant.GCX_WLJWJW)).collect(Collectors.toList());
                    twoList.addAll(recordWdCode);

                    // 当体温大于等于37.4° 当体温>37.4℃，且时间段内有一次或多次测温，则取最高体温值
                    twoList.add(maxRecord);
                    collectsTemperaResult.put(entry.getKey(), twoList);
                    continue;
                }

                //当35<= 体温 =<37.4  优先级4
                if ((compareV2 == 1 || compareV2 == 0) && (compareV == -1 || compareV == 0)) {
                    // 差值最小的记录(当前时间和时间段 那个时间的差值)
                    BObsvRecord chaZhiMinRecord = entry.getValue().stream().filter(code -> !code.getObsvCode().equals(ModelItemConstant.GCX_WLJWJW) && !code.getObsvCode().equals(ModelItemConstant.GCX_CLGJ)).min(Comparator.comparing(BObsvRecord::getDiffSecond)).get();
                    twoList.add(chaZhiMinRecord);

                    List<BObsvRecord> recordWdCode = listAllItemData.stream()
                            .filter(x -> chaZhiMinRecord.getRecTimeStr().equals(x.getRecTimeStr()) && !x.getObsvCode().equals(ModelItemConstant.GCX_T) && !x.getObsvCode().equals(ModelItemConstant.GCX_WLJWJW)).collect(Collectors.toList());
                    //存放对应obsvCode的数据 好对应知道是什么温度
                    twoList.addAll(recordWdCode);
                    collectsTemperaResult.put(entry.getKey(), twoList);
                    continue;
                }
            }
        }
        return collectsTemperaResult;
    }


    @Override
    public Map<String, List<BObsvRecord>> getCollectsPulseHeartRate(String hospitalNumber, String rkTimeStr, String cYTimeStr, List<BObsvRecord> data) {
//        List<BObsvRecord> listPulseHeartRate = yxObsvRecordService.getPulseHeartRateListData(hospitalNumber, rkTimeStr, cYTimeStr);
        List<BObsvRecord> listPulseHeartRate = data;
        if (CollectionUtil.isEmpty(listPulseHeartRate)) {
            listPulseHeartRate = new ArrayList<>();
        }
        //按照时间段分组 把脉搏和心率两个值放在一起
        Map<String, List<BObsvRecord>> collects_PulseHeartRate = listPulseHeartRate.stream().collect(Collectors.groupingBy(BObsvRecord::getDiffHour));

        Map<String, List<BObsvRecord>> collects_PulseHeartRate_result = new LinkedHashMap<>();
        //脉搏和心率相同时，只取脉搏的值，不取心率的值
        for (Map.Entry<String, List<BObsvRecord>> entry : collects_PulseHeartRate.entrySet()) {
            List<BObsvRecord> listData = entry.getValue();

            //数据去重 按照需求 脉搏、心率：脉搏、心率的值取整点（02:00,06:00,10:00,14:00,18:00,22:00）,若无整点数值，则取离整点最近的值
            //这种情况会出现 两个值 比如 21:00 和23:00 离22:00都是 差一个小时 这两个点的数据都是最近的 最终结果要去掉重复的其中一个
            listData = listData.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BObsvRecord::getObsvCode))), ArrayList::new));
            collects_PulseHeartRate_result.put(entry.getKey(), listData);
        }

        return collects_PulseHeartRate_result;
    }

    @Override
    public Map<String, List<BObsvRecord>> getCollectsPulseHeartRate(String hospitalNumber, String rkTimeStr, String cYTimeStr) {
        List<BObsvRecord> listPulseHeartRate = bObsvRecordService.getPulseHeartRateListData(hospitalNumber, rkTimeStr, cYTimeStr);
        //按照时间段分组 把脉搏和心率两个值放在一起
        Map<String, List<BObsvRecord>> collects_PulseHeartRate = listPulseHeartRate.stream().collect(Collectors.groupingBy(BObsvRecord::getDiffHour));

        Map<String, List<BObsvRecord>> collects_PulseHeartRate_result = new LinkedHashMap<>();
        //脉搏和心率相同时，只取脉搏的值，不取心率的值
        for (Map.Entry<String, List<BObsvRecord>> entry : collects_PulseHeartRate.entrySet()) {
            List<BObsvRecord> listData = entry.getValue();

            //数据去重 按照需求 脉搏、心率：脉搏、心率的值取整点（02:00,06:00,10:00,14:00,18:00,22:00）,若无整点数值，则取离整点最近的值
            //这种情况会出现 两个值 比如 21:00 和23:00 离22:00都是 差一个小时 这两个点的数据都是最近的 最终结果要去掉重复的其中一个
            listData = listData.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BObsvRecord::getObsvCode))), ArrayList::new));
            collects_PulseHeartRate_result.put(entry.getKey(), listData);
        }

        return collects_PulseHeartRate_result;
    }

    @Override
    public Map<String, List<BObsvRecord>> getCollectsHuxi(String hospitalNumber, String rkTimeStr, String cYTimeStr, List<BObsvRecord> data) {
        //List<BObsvRecord> list_Breathing = yxObsvRecordService.getTemperatureTOfBreathingListData(hospitalNumber, rkTimeStr, cYTimeStr);
        List<BObsvRecord> list_Breathing = data;
        if (CollectionUtil.isEmpty(list_Breathing)) {
            list_Breathing = new ArrayList<>();
        }

        Map<String, List<BObsvRecord>> collects = list_Breathing.stream().collect(Collectors.groupingBy(BObsvRecord::getDiffHour));

        Map<String, List<BObsvRecord>> collectsResult = new LinkedHashMap<>();
        for (Map.Entry<String, List<BObsvRecord>> entry : collects.entrySet()) {
            //取集合中某个属性最小的那条记录
            List<BObsvRecord> list = entry.getValue();
            List<BObsvRecord> listResult = new ArrayList<>();
            if (list.size() > 0) {
                BObsvRecord minRecord = entry.getValue().stream().min(Comparator.comparing(BObsvRecord::getDiffSecond)).get();
                listResult.add(minRecord);
            }
            collectsResult.put(entry.getKey(), listResult);
        }
        return collectsResult;
    }

    @Override
    public Map<String, List<BObsvRecord>> getCollectsHuxi(String hospitalNumber, String rkTimeStr, String cYTimeStr) {
        List<BObsvRecord> list_Breathing = bObsvRecordService.getTemperatureTOfBreathingListData(hospitalNumber, rkTimeStr, cYTimeStr);
        Map<String, List<BObsvRecord>> collects = list_Breathing.stream().collect(Collectors.groupingBy(BObsvRecord::getDiffHour));

        Map<String, List<BObsvRecord>> collectsResult = new LinkedHashMap<>();

        for (Map.Entry<String, List<BObsvRecord>> entry : collects.entrySet()) {
            //取集合中某个属性最小的那条记录
            List<BObsvRecord> list = entry.getValue();
            List<BObsvRecord> listResult = new ArrayList<>();
            if (list.size() > 0) {
                BObsvRecord minRecord = entry.getValue().stream().min(Comparator.comparing(BObsvRecord::getDiffSecond)).get();
                listResult.add(minRecord);
            }
            collectsResult.put(entry.getKey(), listResult);
        }
        return collectsResult;
    }

    @Override
    public Map<String, List<BObsvRecord>> getCollectsBloodPressure(String hospitalNumber, String rkTimeStr, String cYTimeStr) {
        List<BObsvRecord> listBloodPressure = bObsvRecordService.getBloodPressureListData(hospitalNumber, rkTimeStr, cYTimeStr);
        //按照diffNoon数据分组
        Map<String, List<BObsvRecord>> collectsBloodPressure = listBloodPressure.stream().collect(Collectors.groupingBy(BObsvRecord::getDiffNoon));

        List<BPatEvent> listBloodEvent = bPatEventService.selectEventListForBloodPressure(hospitalNumber, rkTimeStr, cYTimeStr);
        Map<String, List<BPatEvent>> collectsBloodPressureEvent = new LinkedHashMap<>();
        if (listBloodEvent.size() > 0) {
            collectsBloodPressureEvent = listBloodEvent.stream().collect(Collectors.groupingBy(BPatEvent::getDiffNoon));
        }

        Map<String, List<BObsvRecord>> collectsBloodPressureResult = new LinkedHashMap<>();

        for (Map.Entry<String, List<BObsvRecord>> entry : collectsBloodPressure.entrySet()) {
            List<BObsvRecord> listAllData = entry.getValue();
            //有创血压是否有值
            boolean haveYcxy = listAllData.stream().anyMatch(record -> record.getObsvCode().equals(ModelItemConstant.YCXY_SZY) || record.getObsvCode().equals(ModelItemConstant.YCXY_SSY));

            if (haveYcxy) {
                //存在则代码块执行业务逻辑代码 如果有创血压 有值 则去掉无创血压下面的两个值
                listAllData = listAllData.stream().filter(item -> !item.getObsvCode().equals(ModelItemConstant.WCXY_SZY) && !item.getObsvCode().equals(ModelItemConstant.WCXY_SSY)).collect(Collectors.toList());

            }

//        有创血压	gcx_ycxy_s
//        有创舒张压	integer	ibpD
//        有创收缩压	integer	ibpS
            // 无创血压	gcx_wcxy_s
//        无创舒张压	integer	nIbpD
//        无创收缩压	integer	nIbpS

            //如果事件里的diffNoon 包含血压分组里的key  说明这个分组 所在是事件区间里有这个事件的时间，代表这个分组区间里有这个事件发生
            //若有事件发生 （入科、手术） 则展示事件发生后首次的一次血压值
            if (!collectsBloodPressureEvent.isEmpty()) {
                //是否属于同一个段内的时间
                if (collectsBloodPressureEvent.containsKey(entry.getKey())) {

                    //只会有一个事件值
                    List<BPatEvent> listEventOne = collectsBloodPressureEvent.get(entry.getKey());
                    BPatEvent event = listEventOne.get(0);
//                    List<BObsvRecord> data = entry.getValue();

                    BObsvRecord time_data = new BObsvRecord();
                    time_data.setRecTime( PDateUtils.getTimestampOfDateTime(event.getEventTime()));
                    time_data.setRecTimeStr(PDateUtils.timeStamp2Date(PDateUtils.getTimestampOfDateTime(event.getEventTime())  / 1000 + "", "yyyy-MM-dd HH:mm:ss"));
                    listAllData.add(time_data);

                    listAllData.sort(Comparator.comparing(BObsvRecord::getRecTime));
                    //找到这个事件时间前面那个时间的记录时间
                    int indexOfV = 0;
                    for (int i = 0; i < listAllData.size(); i++) {
                        BObsvRecord record = listAllData.get(i);
                        Long recTime = record.getRecTime();
                        Long eventTime = PDateUtils.getTimestampOfDateTime(event.getEventTime());

                        if (recTime.equals(eventTime)) {
                            //若有事件（入院（入科）、手术）发生，则展示发生事件后首次的一次血压值
                            indexOfV = i + 1;
                            break;
                        }
                    }
                    //如果是最后一个
                    if (indexOfV >= listAllData.size()) {
                        //取集合的 最大下标 list下标是从0开始的 所以长度减1
                        indexOfV = listAllData.size() - 1;
                    }
                    BObsvRecord beforeRecord = listAllData.get(indexOfV);
                    List<BObsvRecord> listDataResult = listAllData.stream().filter(r -> r.getRecTime().equals(beforeRecord.getRecTime()) && StringUtil.isNotEmpty(r.getObsvCode())).collect(Collectors.toList());
                    collectsBloodPressureResult.put(entry.getKey(), listDataResult);
                    continue;
                }
            }
            //上午取02:00:00的血压值  下午取 14:00:00的血压值 若无整点 取离整点最近的血压值
            if (entry.getKey().contains("上午")) {
                List<BObsvRecord> timeCha = new ArrayList<>();
                for (int i = 0; i < listAllData.size(); i++) {
                    BObsvRecord record = listAllData.get(i);
                    Date d = null;

                    try {

                        d = DateUtil.parse(record.getRecTimeStr(), "yyyy-MM-dd HH:mm:ss");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    String timeStr = DateUtil.format(d, "HH:mm:ss");
                    if (timeStr.equals("02:00:00")) {
                        List<BObsvRecord> listDataResult = listAllData.stream().filter(r -> r.getRecTime().equals(record.getRecTime())).collect(Collectors.toList());
                        collectsBloodPressureResult.put(entry.getKey(), listDataResult);
                    } else {
                        //只会有一个事件值
                        int chaV = 0;
                        Date dateRecTime = DateUtil.parse(record.getRecTimeStr(), "yyyy-MM-dd HH:mm:ss");
                        String strRecTime = DateUtil.formatDate(dateRecTime);
                        chaV = PDateUtils.compareTwoTime(new Date(record.getRecTime() * 1000), PDateUtils.strToDate(strRecTime + " 02:00:00", "yyyy-MM-dd HH:mm:ss"));
                        record.setChaV(chaV);
                        timeCha.add(record);
                    }
                }
                //算出差值最小的那条记录
                BObsvRecord chazhiMinRecord = listAllData.stream().min(Comparator.comparing(BObsvRecord::getChaV)).get();
                //根据最小差值的那条记录的rectime找到对应两条舒张压和收缩压的数据集合
                List<BObsvRecord> list_data_result = listAllData.stream().filter(r -> r.getRecTime().equals(chazhiMinRecord.getRecTime())).collect(Collectors.toList());
                collectsBloodPressureResult.put(entry.getKey(), list_data_result);
                //1
            } else if (entry.getKey().contains("下午")) {
                List<BObsvRecord> timeCha = new ArrayList<>();
                for (int i = 0; i < listAllData.size(); i++) {
                    BObsvRecord record = listAllData.get(i);
                    Date d;
                    d = DateUtil.parse(record.getRecTimeStr(), "yyyy-MM-dd HH:mm:ss");

                    String timeStr = DateUtil.format(d, "HH:mm:ss");

                    if (timeStr.equals("14:00:00")) {
                        List<BObsvRecord> listDataResult = listAllData.stream().filter(r -> r.getRecTime().equals(record.getRecTime())).collect(Collectors.toList());
                        collectsBloodPressureResult.put(entry.getKey(), listDataResult);
                    } else {
                        //算两个时间差值 观察项记录formatter.parse(s)
                        int chaV = 0;
                        Date dateRecTime = DateUtil.parse(record.getRecTimeStr(), "yyyy-MM-dd HH:mm:ss");
                        String strRecTime = DateUtil.formatDate(dateRecTime);
                        chaV = PDateUtils.compareTwoTime(new Date(record.getRecTime() * 1000), PDateUtils.strToDate(strRecTime + " 14:00:00", "yyyy-MM-dd HH:mm:ss"));
                        record.setChaV(chaV);
                        timeCha.add(record);
                    }
                }
                BObsvRecord chazhiMinRecord = listAllData.stream().min(Comparator.comparing(BObsvRecord::getChaV)).get();
                //根据最小差值的那条记录的rectime找到对应两条舒张压和收缩压的数据集合
                List<BObsvRecord> list_data_result = listAllData.stream().filter(r -> r.getRecTime().equals(chazhiMinRecord.getRecTime())).collect(Collectors.toList());
                collectsBloodPressureResult.put(entry.getKey(), list_data_result);
            }
        }
        return collectsBloodPressureResult;
    }
    
    
    @Override
    public Map<String, List<BObsvRecord>> getCollectsBloodPressure(String hospitalNumber, String rkTimeStr, String cYTimeStr, List<BObsvRecord> data) {
        //List<BObsvRecord> listBloodPressure = yxObsvRecordService.getBloodPressureListData(hospitalNumber, rkTimeStr, cYTimeStr);
        List<BObsvRecord> listBloodPressure = data;
        if (CollectionUtil.isEmpty(listBloodPressure)) {
            listBloodPressure = new ArrayList<>();
        }
        //按照diffNoon数据分组
        Map<String, List<BObsvRecord>> collectsBloodPressure = listBloodPressure.stream().collect(Collectors.groupingBy(BObsvRecord::getDiffNoon));

        List<BPatEvent> listBloodEvent = bPatEventService.selectEventListForBloodPressure(hospitalNumber, rkTimeStr, cYTimeStr);
        Map<String, List<BPatEvent>> collectsBloodPressureEvent = new LinkedHashMap<>();
        if (listBloodEvent.size() > 0) {
            collectsBloodPressureEvent = listBloodEvent.stream().collect(Collectors.groupingBy(BPatEvent::getDiffNoon));
        }

        Map<String, List<BObsvRecord>> collectsBloodPressureResult = new LinkedHashMap<>();

        for (Map.Entry<String, List<BObsvRecord>> entry : collectsBloodPressure.entrySet()) {
            List<BObsvRecord> listAllData = entry.getValue();
            //有创血压是否有值
            boolean haveYcxy = listAllData.stream().anyMatch(record -> record.getObsvCode().equals(ModelItemConstant.YCXY_SZY) || record.getObsvCode().equals(ModelItemConstant.YCXY_SSY));

            if (haveYcxy) {
                //存在则代码块执行业务逻辑代码 如果有创血压 有值 则去掉无创血压下面的两个值
                listAllData = listAllData.stream().filter(item -> !item.getObsvCode().equals(ModelItemConstant.WCXY_SZY) && !item.getObsvCode().equals(ModelItemConstant.WCXY_SSY)).collect(Collectors.toList());

            }

//        有创血压	gcx_ycxy_s
//        有创舒张压	integer	ibpD
//        有创收缩压	integer	ibpS
            // 无创血压	gcx_wcxy_s
//        无创舒张压	integer	nIbpD
//        无创收缩压	integer	nIbpS

            //如果事件里的diffNoon 包含血压分组里的key  说明这个分组 所在是事件区间里有这个事件的时间，代表这个分组区间里有这个事件发生
            //若有事件发生 （入科、手术） 则展示事件发生后首次的一次血压值
            if (!collectsBloodPressureEvent.isEmpty()) {
                //是否属于同一个段内的时间
                if (collectsBloodPressureEvent.containsKey(entry.getKey())) {

                    //只会有一个事件值
                    List<BPatEvent> listEventOne = collectsBloodPressureEvent.get(entry.getKey());
                    BPatEvent event = listEventOne.get(0);
//                    List<BObsvRecord> data = entry.getValue();

                    BObsvRecord time_data = new BObsvRecord();
                    time_data.setRecTime(PDateUtils.getTimestampOfDateTime(event.getEventTime()));
                    // DateUtils.timeStamp2Date(event.getEventTime().getTime() / 1000 + "", "yyyy-MM-dd HH:mm:ss")
                    time_data.setRecTimeStr(event.getEventTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    listAllData.add(time_data);

                    listAllData.sort(Comparator.comparing(BObsvRecord::getRecTime));
                    //找到这个事件时间前面那个时间的记录时间
                    int indexOfV = 0;
                    for (int i = 0; i < listAllData.size(); i++) {
                        BObsvRecord record = listAllData.get(i);
                        Long recTime = record.getRecTime();
                        Long eventTime = PDateUtils.getTimestampOfDateTime(event.getEventTime());

                        if (recTime.equals(eventTime)) {
                            //若有事件（入院（入科）、手术）发生，则展示发生事件后首次的一次血压值
                            indexOfV = i + 1;
                            break;
                        }
                    }
                    //如果是最后一个
                    if (indexOfV >= listAllData.size()) {
                        //取集合的 最大下标 list下标是从0开始的 所以长度减1
                        indexOfV = listAllData.size() - 1;
                    }
                    BObsvRecord beforeRecord = listAllData.get(indexOfV);
                    List<BObsvRecord> listDataResult = listAllData.stream().filter(r -> r.getRecTime().equals(beforeRecord.getRecTime()) && StringUtil.isNotEmpty(r.getObsvCode())).collect(Collectors.toList());
                    collectsBloodPressureResult.put(entry.getKey(), listDataResult);
                    continue;
                }
            }
            //上午取02:00:00的血压值  下午取 14:00:00的血压值 若无整点 取离整点最近的血压值
            if (entry.getKey().contains("上午")) {
                List<BObsvRecord> timeCha = new ArrayList<>();
                for (int i = 0; i < listAllData.size(); i++) {
                    BObsvRecord record = listAllData.get(i);
                    Date d = null;

                    try {

                        d = DateUtil.parse(record.getRecTimeStr(), "yyyy-MM-dd HH:mm:ss");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    String timeStr = DateUtil.format(d, "HH:mm:ss");
                    if (timeStr.equals("02:00:00")) {
                        List<BObsvRecord> listDataResult = listAllData.stream().filter(r -> r.getRecTime().equals(record.getRecTime())).collect(Collectors.toList());
                        collectsBloodPressureResult.put(entry.getKey(), listDataResult);
                    } else {
                        //只会有一个事件值
                        int chaV = 0;
                        Date dateRecTime = DateUtil.parse(record.getRecTimeStr(), "yyyy-MM-dd HH:mm:ss");
                        String strRecTime = DateUtil.formatDate(dateRecTime);
                        chaV = YDateUtils.compareTwoTime(new Date(record.getRecTime() * 1000), YDateUtils.strToDate(strRecTime + " 02:00:00", "yyyy-MM-dd HH:mm:ss"));
                        record.setChaV(chaV);
                        timeCha.add(record);
                    }
                }
                //算出差值最小的那条记录
                BObsvRecord chazhiMinRecord = listAllData.stream().min(Comparator.comparing(BObsvRecord::getChaV)).get();
                //根据最小差值的那条记录的rectime找到对应两条舒张压和收缩压的数据集合
                List<BObsvRecord> list_data_result = listAllData.stream().filter(r -> r.getRecTime().equals(chazhiMinRecord.getRecTime())).collect(Collectors.toList());
                collectsBloodPressureResult.put(entry.getKey(), list_data_result);
                //1
            } else if (entry.getKey().contains("下午")) {
                List<BObsvRecord> timeCha = new ArrayList<>();
                for (int i = 0; i < listAllData.size(); i++) {
                    BObsvRecord record = listAllData.get(i);
                    Date d;
                    d = DateUtil.parse(record.getRecTimeStr(), "yyyy-MM-dd HH:mm:ss");

                    String timeStr = DateUtil.format(d, "HH:mm:ss");

                    if (timeStr.equals("14:00:00")) {
                        List<BObsvRecord> listDataResult = listAllData.stream().filter(r -> r.getRecTime().equals(record.getRecTime())).collect(Collectors.toList());
                        collectsBloodPressureResult.put(entry.getKey(), listDataResult);
                    } else {
                        //算两个时间差值 观察项记录formatter.parse(s)
                        int chaV = 0;
                        Date dateRecTime = DateUtil.parse(record.getRecTimeStr(), "yyyy-MM-dd HH:mm:ss");
                        String strRecTime = DateUtil.formatDate(dateRecTime);
                        chaV = YDateUtils.compareTwoTime(new Date(record.getRecTime() * 1000), YDateUtils.strToDate(strRecTime + " 14:00:00", "yyyy-MM-dd HH:mm:ss"));
                        record.setChaV(chaV);
                        timeCha.add(record);
                    }
                }
                BObsvRecord chazhiMinRecord = listAllData.stream().min(Comparator.comparing(BObsvRecord::getChaV)).get();
                //根据最小差值的那条记录的rectime找到对应两条舒张压和收缩压的数据集合
                List<BObsvRecord> list_data_result = listAllData.stream().filter(r -> r.getRecTime().equals(chazhiMinRecord.getRecTime())).collect(Collectors.toList());
                collectsBloodPressureResult.put(entry.getKey(), list_data_result);
            }
        }
        return collectsBloodPressureResult;
    }


    @Override
    public List<Map> getCollectsShit(String hospitalNumber, String rkTimeStr, String cYTimeStr) {
        List<BObsvRecord> listData = bObsvRecordService.getShitListData(hospitalNumber, rkTimeStr, cYTimeStr);
        List<Map> listRsult = new LinkedList<>();

        //没有被分组的数据
        List<BObsvRecord> listGroupNullResult = new LinkedList<>();


        for (int i = 0; i < listData.size(); i++) {

            if (listData.get(i).getDiffDay().equals("null")) {
                //2022-02-18-2022-02-19
                BObsvRecord dataNull = listData.get(i);
                String diffDay = "";
                String recTimeStr = dataNull.getRecTimeStr();

                // 格式化时间 2018-07-17
                Date date;

                date = DateUtil.parseDate(recTimeStr);

                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                //把日期往后增加一天,整数  往后推,负数往前移动
                calendar.add(Calendar.DATE, 1);
                //这个时间就是日期往后推一天的结果
                Date dateAdd = calendar.getTime();

                String timeStr = DateUtil.formatDate(date) + "-" + DateUtil.formatDate(dateAdd);
                dataNull.setDiffDay(timeStr);
                listGroupNullResult.add(dataNull);
            } else {
                BObsvRecord data = listData.get(i);
                listGroupNullResult.add(data);
            }

        }


        //按照diffDay 列分组
        Map<String, List<BObsvRecord>> collectsShit = listGroupNullResult.stream().collect(Collectors.groupingBy(BObsvRecord::getDiffDay));
        for (Map.Entry<String, List<BObsvRecord>> entry : collectsShit.entrySet()) {

            List<BObsvRecord> list_group = entry.getValue();

            //是否 人工肛门
            boolean haveZkrggm = list_group.stream().anyMatch(record -> record.getObsvCode().equals(ModelItemConstant.GCX_RKGM) && StringUtils.isNotEmpty(record.getPropValue()));

            //是否失禁
            boolean haveGcxSfsj = list_group.stream().anyMatch(record -> record.getObsvCode().equals(ModelItemConstant.GCX_SFSJ) && StringUtils.isNotEmpty(record.getPropValue()));

            if (haveZkrggm) {
                Map map = new LinkedHashMap();
                map.put(entry.getKey(), "☆");
                listRsult.add(map);
                continue;
            }
            if (haveGcxSfsj) {
                Map map = new LinkedHashMap();
                map.put(entry.getKey(), "※");
                listRsult.add(map);
                continue;
            } else {
                //同一分组内的数据 过滤逻辑
                //这种情况 是没有 是否失禁和造口/人工肛门 的情况 单纯统计大便次数的逻辑


                //自主排便次数-灌肠后排便次数/灌肠标识
                //4-4/E
                // gcx_dbcs
                List<BObsvRecord> obsvDbcsList = list_group.stream().filter(gcx_dbcs -> gcx_dbcs.getObsvCode().equals("gcx_dbcs")&&StringUtil.isNotEmpty(gcx_dbcs.getPropValue())).collect(Collectors.toList());
                //gcx_gchpbcs 灌肠后排便次数
                List<BObsvRecord> obsvGchpbcsList = list_group.stream().filter(gcx_dbcs -> gcx_dbcs.getObsvCode().equals("gcx_gchpbcs")&&StringUtil.isNotEmpty(gcx_dbcs.getPropValue())).collect(Collectors.toList());

//                Long dbcsSum=obsvDbcsList.stream().collect(Collectors.summingLong(BObsvRecord::getPropValue));
//                int salaryTotal = obsvDbcsList.stream().collect(Collectors.summingInt(BObsvRecord::getPropValue));
                int dbcsSum=0;
                StringBuilder dbcsSumStr=new StringBuilder();
                for (int i = 0; i <obsvDbcsList.size() ; i++) {
                    BObsvRecord obsvRecord=obsvDbcsList.get(i);
                    String propValue=obsvRecord.getPropValue();
                    int value=Integer.valueOf(propValue);
                    dbcsSum=dbcsSum+value;
                    dbcsSumStr.append(propValue);
                }
                int gchpbcsSum=0;
                StringBuilder gchpbcsSumStr=new StringBuilder();
                for (int i = 0; i <obsvGchpbcsList.size() ; i++) {
                    BObsvRecord obsvRecord=obsvGchpbcsList.get(i);
                    //12/E
                    String propValue=obsvRecord.getPropValue().replace("/E","");
                    int value=Integer.valueOf(propValue);
                    gchpbcsSum=gchpbcsSum+value;
                    gchpbcsSumStr.append(propValue);
                }
//                String
                String result="";
                if(dbcsSum==0&&StringUtil.isEmpty(gchpbcsSumStr.toString() )) {
                    //如果大便次数为0 灌肠后排便次数为空不填写
                    result = dbcsSum + "";

                }else   if(StringUtil.isEmpty(dbcsSumStr.toString() )&&StringUtil.isEmpty(gchpbcsSumStr.toString())){
                    //如果大便次数和灌肠后大便次数为空那么结果就为空
                    result="";
                }else   if(StringUtil.isEmpty(dbcsSumStr.toString() )&&gchpbcsSum==0){
                    // 如果时间范围内大便次数都不填写 灌肠后排便次数总数为0
                    result="0-0/E";
                }else   if(dbcsSum==0&&gchpbcsSum==0){
                    result="0-0/E";
                }else   if(dbcsSum!=0&&StringUtil.isEmpty(gchpbcsSumStr.toString())){
                    result=dbcsSum+"";
                }else{
                    result= dbcsSum+"-"+gchpbcsSum+"/E";
                }

//                value = TemperatureUtil.getShitModelValue(obsvDbcsList);
                Map map = new LinkedHashMap();
                map.put(entry.getKey(), result);
                listRsult.add(map);
            }

        }
        return listRsult;
    }


    @Override
    public List<TemperateIODataVO> getListOutNl(String hospitalNumber, String rkTimeStr, String cYTimeStr) {
        List<TemperateIODataVO> listNl = bIoRecordService.selectSumOfNlList(hospitalNumber, ModelItemConstant.CRL_OUT_NL, rkTimeStr, cYTimeStr);


        //查询 管道管理中该患者是否有使用低危导管中的“导尿管”
//        List<YxPipeUseRecordPO> list_pipedata = yxPipeUseRecordService.selectUseDataOfHospitalNumber("低危导管", "导尿管", hospitalNumber);
        List<TepPipeUseRecordVO> pipe = bPipeUseRecordService.selectTemperatureChannelByHospitalNumberAndTime(hospitalNumber,rkTimeStr,cYTimeStr,"导尿");
        Set<String> times = new HashSet<>();
        if(CollectionUtil.isNotEmpty(pipe)){
            for (TepPipeUseRecordVO vo : pipe){
                Date startTime =YDateUtils.strToDate(YDateUtils.dateToDayStr(vo.getImbedTime())+" 00:00:00",YDateUtils.DATE_TIME_PATTERN);
                Date endTime = YDateUtils.strToDate(YDateUtils.dateToDayStr(vo.getPullTime())+" 00:00:00",YDateUtils.DATE_TIME_PATTERN);
                Long count = YDateUtils.getDays(startTime,endTime)+1;
                for(int i = 0 ; i < count ; i++){
                    times.add(YDateUtils.dateToDayStr(startTime));
                    startTime = YDateUtils.addDateDays(startTime,1);
                }
            }
        }
        List<TemperateIODataVO> nlResult = new LinkedList<>();
        if (CollectionUtil.isNotEmpty(times)) {
            for (int i = 0; i < listNl.size(); i++) {
                TemperateIODataVO data = listNl.get(i);
                if(times.contains(data.getDiffDay().substring(0,10))){
                    //去掉多余的0
                    data.setSumValue(YDateUtils.trimNoZeros(data.getSumValue()) + "/C");
                }
                else{
                    data.setSumValue(YDateUtils.trimNoZeros(data.getSumValue()) );
                }
                nlResult.add(data);
            }
        } else {
            listNl.forEach(object -> object.setSumValue(YDateUtils.trimNoZeros(object.getSumValue())));
            nlResult.addAll(listNl);
        }
        return nlResult;
    }
}
